package cn.jixie.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 检查微信与服务器连接
 */
public class CheckConnectUtils {

    private static final String token = "hjlzl"; // 微信公众号的token


    public static boolean checkConnectWithWechat(String signature,String timestamp,
                                                 String nonce){

        String[] arr = new String[]{token,signature,timestamp};
        //排序
        Arrays.sort(arr);
        //生成字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (String string : arr){
            stringBuilder.append(string);
        }
        //加密 sha1
        String encodeString = passSha1Encode(stringBuilder.toString());
        if(signature.equals(encodeString)){
            return true;
        }else{
            return false;
        }

    }

    public static String passSha1Encode(String string){
        if (string == null || string.length() == 0){
            return null;
        }
        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d'
        ,'e','f'
        };
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(string.getBytes());
            byte[] md = messageDigest.digest();
            int j = md.length;
            char[] buf = new char[j*2];
            int k = 0;
            for(int i=0 ; i <j ; i++){
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>>4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        }catch (NoSuchAlgorithmException e){
            return null;
        }
    }



}
